<template>
  <div class="form-fill">
    <!-- 加载状态 -->
    <div v-if="loading" class="loading-container">
      <el-icon class="is-loading" :size="64"><Loading /></el-icon>
      <p>加载表单中...</p>
    </div>

    <!-- 错误状态 -->
    <div v-else-if="error" class="error-container">
      <el-icon :size="64" color="#f56c6c"><WarningFilled /></el-icon>
      <h3>{{ error }}</h3>
      <el-button @click="retry">重试</el-button>
    </div>

    <!-- 表单内容 -->
    <div v-else class="form-container">
      <!-- 表单头部 -->
      <div class="form-header">
        <h1>{{ formData.title || '未命名表单' }}</h1>
        <p v-if="formData.description" class="form-description">{{ formData.description }}</p>
      </div>

      <!-- 表单字段 -->
      <div class="form-fields">
        <div v-if="formData.fields && formData.fields.length === 0" class="empty-form">
          <el-icon :size="64"><DocumentAdd /></el-icon>
          <p>此表单暂无字段</p>
        </div>
        
        <el-form 
          v-else 
          :model="formModel" 
          ref="formRef" 
          label-position="top"
        >
          <div 
            v-for="(field, index) in formData.fields" 
            :key="field.id"
            class="field-item"
          >
            <!-- 文本输入 -->
            <el-form-item 
              v-if="field.type === 'text' || field.type === 'email' || field.type === 'phone'"
              :label="field.label" 
              :required="field.required"
              :prop="`field_${field.id}`"
            >
              <el-input 
                v-model="formModel[`field_${field.id}`]"
                :placeholder="field.placeholder"
                clearable
              />
              <div v-if="field.helpText" class="field-help">{{ field.helpText }}</div>
            </el-form-item>

            <!-- 多行文本 -->
            <el-form-item 
              v-else-if="field.type === 'textarea'"
              :label="field.label" 
              :required="field.required"
              :prop="`field_${field.id}`"
            >
              <el-input 
                v-model="formModel[`field_${field.id}`]"
                type="textarea"
                :placeholder="field.placeholder"
                :rows="4"
                clearable
              />
              <div v-if="field.helpText" class="field-help">{{ field.helpText }}</div>
            </el-form-item>

            <!-- 数字输入 -->
            <el-form-item 
              v-else-if="field.type === 'number'"
              :label="field.label" 
              :required="field.required"
              :prop="`field_${field.id}`"
            >
              <el-input-number 
                v-model="formModel[`field_${field.id}`]"
                :placeholder="field.placeholder"
                style="width: 100%"
                controls-position="right"
              />
              <div v-if="field.helpText" class="field-help">{{ field.helpText }}</div>
            </el-form-item>

            <!-- 单选题 -->
            <el-form-item 
              v-else-if="field.type === 'radio'"
              :label="field.label" 
              :required="field.required"
              :prop="`field_${field.id}`"
            >
              <el-radio-group v-model="formModel[`field_${field.id}`]">
                <el-radio 
                  v-for="option in field.options" 
                  :key="option.value"
                  :label="option.value"
                >
                  {{ option.label }}
                </el-radio>
              </el-radio-group>
              <div v-if="field.helpText" class="field-help">{{ field.helpText }}</div>
            </el-form-item>

            <!-- 多选题 -->
            <el-form-item 
              v-else-if="field.type === 'checkbox'"
              :label="field.label" 
              :required="field.required"
              :prop="`field_${field.id}`"
            >
              <el-checkbox-group v-model="formModel[`field_${field.id}`]">
                <el-checkbox 
                  v-for="option in field.options" 
                  :key="option.value"
                  :label="option.value"
                >
                  {{ option.label }}
                </el-checkbox>
              </el-checkbox-group>
              <div v-if="field.helpText" class="field-help">{{ field.helpText }}</div>
            </el-form-item>

            <!-- 下拉选择 -->
            <el-form-item 
              v-else-if="field.type === 'select'"
              :label="field.label" 
              :required="field.required"
              :prop="`field_${field.id}`"
            >
              <el-select 
                v-model="formModel[`field_${field.id}`]"
                :placeholder="field.placeholder"
                style="width: 100%"
                clearable
              >
                <el-option 
                  v-for="option in field.options" 
                  :key="option.value"
                  :label="option.label"
                  :value="option.value"
                />
              </el-select>
              <div v-if="field.helpText" class="field-help">{{ field.helpText }}</div>
            </el-form-item>

            <!-- 日期选择 -->
            <el-form-item 
              v-else-if="field.type === 'date'"
              :label="field.label" 
              :required="field.required"
              :prop="`field_${field.id}`"
            >
              <el-date-picker 
                v-model="formModel[`field_${field.id}`]"
                type="date"
                :placeholder="field.placeholder"
                style="width: 100%"
              />
              <div v-if="field.helpText" class="field-help">{{ field.helpText }}</div>
            </el-form-item>

            <!-- 评分 -->
            <el-form-item 
              v-else-if="field.type === 'rating'"
              :label="field.label" 
              :required="field.required"
              :prop="`field_${field.id}`"
            >
              <el-rate 
                v-model="formModel[`field_${field.id}`]"
                :max="field.max || 5"
                show-text
              />
              <div v-if="field.helpText" class="field-help">{{ field.helpText }}</div>
            </el-form-item>
          </div>
        </el-form>
      </div>

      <!-- 提交按钮 -->
      <div v-if="formData.fields && formData.fields.length > 0" class="form-actions">
        <el-button 
          type="primary" 
          size="large" 
          @click="submitForm"
          :loading="submitting"
          :disabled="formData.status !== 1"
        >
          {{ submitting ? '提交中...' : '提交表单' }}
        </el-button>
        <p v-if="formData.status !== 1" class="submit-tip">
          表单未发布或已关闭，无法提交
        </p>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import { 
  Loading, WarningFilled, DocumentAdd
} from '@element-plus/icons-vue'
import { getPublicForm, submitForm as submitFormApi } from '@/plugin/gva_intelligent_form/api/form.js'

const route = useRoute()

// 状态管理
const loading = ref(true)
const error = ref('')
const submitting = ref(false)

// 表单数据
const formData = ref({
  title: '',
  description: '',
  fields: [],
  status: 0
})

// 表单模型
const formModel = ref({})
const formRef = ref()

// 初始化表单模型
const initFormModel = () => {
  const model = {}
  formData.value.fields.forEach(field => {
    if (field.type === 'checkbox') {
      model[`field_${field.id}`] = []
    } else {
      model[`field_${field.id}`] = ''
    }
  })
  formModel.value = model
}

// 重试加载
const retry = () => {
  error.value = ''
  loadForm()
}

// 加载表单数据
const loadForm = async () => {
  loading.value = true
  error.value = ''
  
  try {
    const formId = route.params.id
    if (!formId) {
      throw new Error('表单ID不能为空')
    }

    const res = await getPublicForm(formId)
    if (res.code === 0) {
      // 从formConfig中提取fields
      const formConfig = res.data.formConfig || {}
      const fields = formConfig.fields || []
      
      formData.value = {
        title: res.data.title || '',
        description: res.data.description || '',
        status: res.data.status || 0,
        fields: fields
      }
      
      // 初始化表单模型
      initFormModel()
      
    } else {
      throw new Error(res.msg || '获取表单失败')
    }
  } catch (err) {
    console.error('加载表单失败:', err)
    error.value = err.message || '加载表单失败，请稍后重试'
  } finally {
    loading.value = false
  }
}

// 提交表单
const submitForm = async () => {
  submitting.value = true
  
  try {
    // 构造提交数据
    const submitData = {
      formId: parseInt(route.params.id),
      submitData: formModel.value
    }
    
    const res = await submitFormApi(submitData)
    if (res.code === 0) {
      ElMessage.success('表单提交成功！')
      // 重置表单
      initFormModel()
    } else {
      throw new Error(res.msg || '提交失败')
    }
  } catch (error) {
    ElMessage.error(error.message || '提交失败，请稍后重试')
  } finally {
    submitting.value = false
  }
}

onMounted(() => {
  loadForm()
})
</script>

<style scoped>
.form-fill {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 40px 20px;
}

/* 加载状态 */
.loading-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  min-height: 400px;
  color: white;
  text-align: center;
}

.loading-container p {
  margin-top: 16px;
  font-size: 16px;
}

/* 错误状态 */
.error-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  min-height: 400px;
  color: white;
  text-align: center;
}

.error-container h3 {
  margin: 16px 0 24px 0;
  font-size: 18px;
}

/* 表单容器 */
.form-container {
  max-width: 800px;
  margin: 0 auto;
  background: white;
  border-radius: 16px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

/* 表单头部 */
.form-header {
  padding: 48px 48px 32px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  text-align: center;
}

.form-header h1 {
  margin: 0 0 16px 0;
  font-size: 32px;
  font-weight: 600;
  line-height: 1.2;
}

.form-description {
  margin: 0;
  font-size: 16px;
  opacity: 0.9;
  line-height: 1.6;
}

/* 表单字段 */
.form-fields {
  padding: 40px 48px;
}

.empty-form {
  text-align: center;
  padding: 60px 20px;
  color: #909399;
}

.empty-form p {
  margin: 16px 0 0 0;
  font-size: 16px;
}

.field-item {
  margin-bottom: 32px;
}

.field-help {
  margin-top: 8px;
  font-size: 13px;
  color: #909399;
  line-height: 1.4;
}

/* 表单操作 */
.form-actions {
  padding: 32px 48px 48px;
  text-align: center;
  border-top: 1px solid #f0f0f0;
  background: #fafbfc;
}

.submit-tip {
  margin: 16px 0 0 0;
  font-size: 14px;
  color: #909399;
}

/* Element Plus 组件样式调整 */
:deep(.el-form-item__label) {
  font-weight: 600;
  color: #303133;
  margin-bottom: 12px;
  font-size: 15px;
}

:deep(.el-form-item) {
  margin-bottom: 28px;
}

:deep(.el-radio) {
  margin-right: 24px;
  margin-bottom: 12px;
}

:deep(.el-checkbox) {
  margin-right: 24px;
  margin-bottom: 12px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .form-fill {
    padding: 20px 16px;
  }
  
  .form-container {
    margin: 0;
    border-radius: 12px;
  }
  
  .form-header {
    padding: 32px 24px 24px;
  }
  
  .form-header h1 {
    font-size: 24px;
  }
  
  .form-fields,
  .form-actions {
    padding: 24px;
  }
}

/* 提交按钮样式 */
.form-actions .el-button {
  padding: 16px 48px;
  font-size: 16px;
  font-weight: 600;
  border-radius: 24px;
  min-width: 200px;
}

.form-actions .el-button--primary {
  background: linear-gradient(135deg, #409eff 0%, #667eea 100%);
  border: none;
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.3);
}
</style> 